#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
提示词生成器集成测试

测试整个提示词生成器的工作流程，确保所有组件能够协同工作。
"""

import unittest
import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))

from src.text.prompt_generator import prompt_generator
from src.text.prompt_generator import prompt_template_manager
from src.text.prompt_generator import information_fusion_processor
from src.text.prompt_generator import prompt_generation_engine
from src.text.prompt_generator import prompt_optimizer


class IntegrationTestPromptGenerator(unittest.TestCase):
    """
    提示词生成器集成测试类
    """
    
    def setUp(self):
        """
        测试前的设置
        """
        # 获取各个组件的实例
        self.template_manager = prompt_template_manager.get_prompt_template_manager()
        self.fusion_processor = information_fusion_processor.get_information_fusion_processor()
        self.generation_engine = prompt_generation_engine.get_prompt_generation_engine()
        self.optimizer = prompt_optimizer.get_prompt_optimizer()
        self.generator = prompt_generator.get_prompt_generator()
    
    def test_full_prompt_generation_flow(self):
        """
        测试完整的提示词生成流程
        """
        # 准备测试数据
        visual_analysis = {
            "video_id": "integration_test_video_001",
            "scene_setting": "校园场景",
            "objects": ["学生", "教室", "黑板", "讲台"],
            "activities": ["上课", "学习", "听讲"]
        }
        
        # 1. 测试信息融合
        fusion_result = self.fusion_processor.fuse_information(visual_analysis)
        self.assertIsInstance(fusion_result, dict)
        self.assertIn("known_fields", fusion_result)
        self.assertIn("missing_fields", fusion_result)
        self.assertIn("context", fusion_result)
        
        # 2. 测试模板获取
        template = self.template_manager.get_template("scene_setting")
        self.assertIsInstance(template, str)
        self.assertTrue(len(template) > 0)
        
        # 3. 测试提示词生成
        content = fusion_result["known_fields"].get("scene_setting", "")
        generated_prompt = self.generation_engine.generate_prompt(
            "scene_setting", 
            content, 
            fusion_result["context"]
        )
        self.assertIsInstance(generated_prompt, str)
        self.assertTrue(len(generated_prompt) > 0)
        
        # 4. 测试提示词优化
        keywords = ["校园", "学生", "教室", "黑板"]
        optimized_prompt = self.optimizer.optimize_prompt(generated_prompt, keywords)
        self.assertIsInstance(optimized_prompt, str)
        self.assertTrue(len(optimized_prompt) > 0)
        
        # 5. 测试完整的生成器流程
        final_prompt = self.generator.generate_prompt("scene_setting", visual_analysis)
        self.assertIsInstance(final_prompt, str)
        self.assertTrue(len(final_prompt) > 0)
    
    def test_missing_categories_generation(self):
        """
        测试生成缺失类目提示词的流程
        """
        # 准备测试数据（只有场景设置，缺少其他类目）
        visual_analysis = {
            "video_id": "integration_test_video_002",
            "scene_setting": "公园场景",
            "objects": ["树木", "长椅", "游客"],
            "activities": ["散步", "休息"]
        }
        
        # 测试生成缺失类目提示词
        missing_prompts = self.generator.generate_missing_prompts(visual_analysis)
        
        self.assertIsInstance(missing_prompts, dict)
        # 至少应该为一个缺失的类目生成提示词
        self.assertTrue(len(missing_prompts) > 0)
        
        # 验证每个生成的提示词
        for category, prompt in missing_prompts.items():
            self.assertIsInstance(category, str)
            self.assertIsInstance(prompt, str)
            self.assertTrue(len(prompt) > 0)
    
    def test_all_categories_generation(self):
        """
        测试生成所有类目提示词的流程
        """
        # 准备测试数据
        visual_analysis = {
            "video_id": "integration_test_video_003",
            "scene_setting": "商场场景",
            "theme_type": "购物",
            "objects": ["商店", "顾客", "商品"],
            "activities": ["购物", "浏览"]
        }
        
        # 测试生成所有类目提示词
        all_prompts = self.generator.generate_all_prompts(visual_analysis)
        
        self.assertIsInstance(all_prompts, dict)
        # 至少应该包含scene_setting的提示词
        self.assertIn("scene_setting", all_prompts)
        
        # 验证每个生成的提示词
        for category, prompt in all_prompts.items():
            self.assertIsInstance(category, str)
            self.assertIsInstance(prompt, str)
            self.assertTrue(len(prompt) > 0)
    
    def test_error_handling(self):
        """
        测试错误处理机制
        """
        # 测试空输入
        empty_analysis = {}
        
        # 应该能够处理空输入而不崩溃
        try:
            result = self.generator.generate_missing_prompts(empty_analysis)
            self.assertIsInstance(result, dict)
        except Exception as e:
            self.fail(f"生成器在处理空输入时抛出了异常: {str(e)}")
        
        # 测试无效类目
        try:
            result = self.generator.generate_prompt("invalid_category", empty_analysis)
            self.assertIsInstance(result, str)
        except Exception as e:
            self.fail(f"生成器在处理无效类目时抛出了异常: {str(e)}")


if __name__ == "__main__":
    unittest.main()